package com.pubinfo.passbook.common.service.dubbo.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.pubinfo.passbook.common.exception.ServiceException;
import com.pubinfo.passbook.common.mapper.TSubsidiaryInfoMapper;
import com.pubinfo.passbook.common.model.bo.eip.ReceiveTaskParam;
import com.pubinfo.passbook.common.model.bo.eip.ReceiveTaskResult;
import com.pubinfo.passbook.common.model.bo.uccp.ShortMessageParam;
import com.pubinfo.passbook.common.model.bo.witeoff.CityInfo;
import com.pubinfo.passbook.common.model.constant.RedisKey;
import com.pubinfo.passbook.common.model.dubbo.ESBServiceData;
import com.pubinfo.passbook.common.model.eop.ApplyParam;
import com.pubinfo.passbook.common.model.shortMessage.QueryMessageBodyParam;
import com.pubinfo.passbook.common.model.shortMessage.QueryMessageReply;
import com.pubinfo.passbook.common.model.shortMessage.ShortMessageBodyReply;
import com.pubinfo.passbook.common.model.vo.base.JsonResult;
import com.pubinfo.passbook.common.service.cache.JedisManage;
import com.pubinfo.passbook.common.service.dubbo.DubboService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@SuppressWarnings("ALL")
@Slf4j
@Service
public class DubboServiceImpl implements DubboService {
    private int seconds = 1000 * 60 * 60 * 24;
  @Value("${post.url}")
  String postUrl;

    @Resource
    JedisManage jedisManage;

    @Value("${post.dubbo-port}")
    String dubboPort;

    @Override
    public String getPersonsDetailByStatus(String idNo) {

        return getPersonsDetailByIdNo(idNo).getStaffStatus();
    }

    @Override
    public ESBServiceData.CertDetail getPersonsDetailByIdNo(String idNo) {
        String reply = jedisManage.getStr(RedisKey.USER_NO_ID + idNo);
        if (StringUtils.isBlank(reply)) {
          reply = getPersonsDetailByAcct(new ESBServiceData.Cert(idNo), 1);
          jedisManage.putStr(RedisKey.USER_NO_ID + idNo, seconds, reply);
        }
        JsonResult<Collection<ESBServiceData.CertDetail>> jsonResult = JSONObject.toJavaObject(JSON.parseObject(reply), JsonResult.class);
        if (!CollectionUtils.isEmpty(jsonResult.getResult())) {
            Collection<ESBServiceData.CertDetail> certDetails = jsonResult.getResult();
            List<ESBServiceData.CertDetail> cartItems =
                    JSONArray.parseArray(JSON.toJSONString(certDetails), ESBServiceData.CertDetail.class);
            return cartItems.get(0);
        }
        return null;
    }

    @Override
    public String getPersonsDetailByAcct(String idNo) {
        ESBServiceData.CertDetail certDetail = getPersonsDetailByIdNo(idNo);
        return certDetail != null ? certDetail.getStaffCode() : null;
    }

    @SneakyThrows
    public String getPersonsDetailByAcct(ESBServiceData.Cert cert, Integer count) {
        String reply = sendDubboPost(JSONObject.toJSONString(cert), "/api/esb/get");
        JsonResult<Collection<ESBServiceData.CertDetail>> jsonResult = JSONObject.toJavaObject(JSON.parseObject(reply), JsonResult.class);
        if (count < 3 && jsonResult.getStatus() == 500) {
            Thread.sleep(1500L);
            getPersonsDetailByAcct(cert, count++);
        }
        return reply;
    }

    private String sendDubboPost(String s, String url) {

        return sendPost(s, postUrl + ":" + dubboPort + url);
    }

    @Override
    public JsonResult<Collection<ESBServiceData.CertDetail>> getPersonsDetailByAcct(ESBServiceData.Cert cert) {

        String reply = sendDubboPost(JSONObject.toJSONString(cert), "/api/esb/get");

        return JSONObject.toJavaObject(JSON.parseObject(reply), JsonResult.class);
    }

    private String sendPost(String s, String url) {
        //Unirest.setTimeouts(0, 0);
        HttpResponse<String> response = null;
        try {
            response = Unirest.post(url)
                    .header("User-Agent", "apifox/1.0.0 (https://www.apifox.cn)")
                    .header("Content-Type", "application/json")
                    .header("Accept-Encoding", "gzip, deflate, br")
                    .body(s)
                    .asString();
        } catch (UnirestException e) {
            throw new ServiceException("调用服务失败", e);
        }
        return response.getBody();
    }

    @Override
    public Boolean sendShortMessage(ShortMessageParam param) {
        String reply = sendDubboPost(JSONObject.toJSONString(param), "/api/uccp/sendShortMessage");
        ShortMessageBodyReply bodyReply = JSONObject.toJavaObject(JSON.parseObject(reply), ShortMessageBodyReply.class);
        if ("0000".equals(bodyReply.getCode().trim())) {
            //成功后逻辑
            return true;
        }
      JSONObject.parseObject(reply);
      return false;
    }
  
  @Override
  public QueryMessageReply queryMessage(QueryMessageBodyParam param) {
    String reply = sendDubboPost(JSONObject.toJSONString(param), "/api/uccp/queryMessage");
    QueryMessageReply bodyReply = JSONObject.toJavaObject(JSON.parseObject(reply), QueryMessageReply.class);
    return bodyReply;
  }
  
  @Override
  public String orderApply(ApplyParam applyParam) {
    try {
      long startTime = System.currentTimeMillis();
      String reply = sendDubboPost(JSONObject.toJSONString(applyParam), "/api/eop/placeOrder");
      JSONObject result = JSONObject.parseObject(reply);
      log.info("申请开票 RESULT :{}", result);
      if ("1".equals(result.getJSONObject("msghead").getString("result_code"))) {
        
        if ("0".equals(result.getJSONObject("msgbody").getString("resultCode"))) {
          
          return "SUCCESS";
        } else {
          return result.getJSONObject("msgbody").getString("resultMsg");
        }
      }
      log.info("统一平台订单受理接口==========> {} MS", System.currentTimeMillis() - startTime);
    } catch (Exception e) {
      log.error("申请开票失败 :{}", e.getMessage());
    }
    return "调用接口失败";
  }
  
  @Autowired
  TSubsidiaryInfoMapper infoMapper;
  
  @Override
  public String getUserNsrsbhByAcct(String acct) {
    
    ESBServiceData.CertDetail certDetail = getPersonsDetailByIdNo(acct);
    if (certDetail == null) {
      throw new ServiceException("该账号在人力系统不存在！请找系统管理员咨询");
    }

        //公司名称
        String areaName = certDetail.getCountyName();

        CityInfo info = infoMapper.findCityInfoByNsrsbh(areaName);
        return info.getNsrsbh();
    }


    @Override
    public ReceiveTaskResult receiveTaskInfo(ReceiveTaskParam taskParam) {
        List<ReceiveTaskParam> taskParams = new ArrayList<>();
        taskParams.add(taskParam);
        String reply = sendDubboPost(JSONObject.toJSONString(taskParams), "/api/eip/receiveTaskInfo");
        ReceiveTaskResult bodyReply = JSONObject.toJavaObject(JSON.parseObject(reply), ReceiveTaskResult.class);
        return bodyReply;
    }

    @Override
    public ReceiveTaskResult finishedTask(String taskId) {
        String reply = sendDubboPost(taskId, "/api/eip/finishedTask");
        ReceiveTaskResult bodyReply = JSONObject.toJavaObject(JSON.parseObject(reply), ReceiveTaskResult.class);
        return bodyReply;
    }
}
